package org.springblade.modules.admin.task.feishu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.FeiShuDocumentEnum;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.feishu.FeiShuBatchDTO;
import org.springblade.modules.admin.dto.feishu.FeiShuFieldsDTO;
import org.springblade.modules.admin.dto.plan.PlanSearchDTO;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.service.feishu.IFeiShuDocumentService;
import org.springblade.modules.admin.vo.plan.PlanListVo;
import org.springblade.modules.admin.vo.plan.PlanSignStatusVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 凤仪的飞书保养工单-逾期风险数据表，仅银河租户
 * @author: Sharry
 * @createTime: 2024-05-14 14:49
 * @version: Version-1.0
 */

@Component
@Slf4j
public class LarkElevatorMaintenanceOverdueDataJob {

	@Autowired
	private IMaintainPlanContentService maintainPlanContentService;

	@Autowired
	private IFeiShuDocumentService feiShuDocumentService;

	@XxlJob("galaxyElevatorMaintenanceOverdueDataJobCopy")
	public void galaxyElevatorMaintenanceOverdueDataJobCopy(){
		XxlJobHelper.handleSuccess("定时任务更新凤仪的飞书保养工单-逾期风险数据表-[执行]开始");
		try{
			// 1. 数据准备：appToken，tableId，构造查询条件，复用分页查询逻辑，稍作修改，查询全部数据
			String appToken = FeiShuDocumentEnum.ELEVATOR_MAINTENANCE_OVERDUE_DATA_COPY.getAppToken();
			String tableId = FeiShuDocumentEnum.ELEVATOR_MAINTENANCE_OVERDUE_DATA_COPY.getTableId();
			feiShuDocumentService.commandDistinctByKeyAndUpdateTime(appToken,tableId,"梯无忧_保养工单任务ID","最后更新时间");
			PlanSearchDTO planSearchDTO = new PlanSearchDTO();
			planSearchDTO.setCurrent(null);
			planSearchDTO.setSize(null);
			Date beginTime = new Date(0L);
			// 当天 23:59:59
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.HOUR_OF_DAY, 23);
			calendar.set(Calendar.MINUTE, 59);
			calendar.set(Calendar.SECOND, 59);
			Date endTime = calendar.getTime();
			planSearchDTO.setBeginCreateTime(beginTime);
			planSearchDTO.setEndCreateTime(endTime);
			List<Integer> planStatusList = new ArrayList<>();
			// 待开始+进行中+已提交
			planStatusList.add(TaskStatusEnum.BY_DISABLE.getStatus());
			planStatusList.add(TaskStatusEnum.BY_PROCESSED.getStatus());
			planStatusList.add(TaskStatusEnum.BY_FINISH.getStatus());
			planSearchDTO.setPlanStatus(planStatusList);
			List<PlanListVo> targetList = maintainPlanContentService.planListNewLark(planSearchDTO);

			// 2. 数据封装、数据处理
			FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
			List<FeiShuFieldsDTO> records = new ArrayList<>();
			for (PlanListVo planListVo : targetList) {
				FeiShuFieldsDTO element = new FeiShuFieldsDTO();
				Map<String, Object> elementMap = new HashMap<>(30);
				elementMap.put("梯无忧_保养工单任务ID", String.valueOf(planListVo.getPlanId()));
				elementMap.put("梯无忧_电梯快速识别码", planListVo.getElevatorNum());
				// 执行人
				if(!Func.isNull(planListVo.getRealNames())){
					String[] realNamesArray = planListVo.getRealNames().split(",");
					elementMap.put("执行人", realNamesArray);
				}
				// 实际执行人
				List<PlanSignStatusVo> planSignStatusList = planListVo.getPlanSignStatusList();
				List<String> actualExecuteList = new ArrayList<>();
				if(!Func.isEmpty(planSignStatusList)){
					planSignStatusList.stream().map(PlanSignStatusVo::getUserName).forEach(actualExecuteList::add);
					elementMap.put("实际执行人", actualExecuteList.toArray(new String[0]));
				}
				// 已签字维保员
				List<String> signedList = new ArrayList<>();
				if(!Func.isNull(planListVo.getSignNames())){
					String[] signedListSplit = planListVo.getSignNames().split(",");
					signedList = Arrays.asList(signedListSplit);
					elementMap.put("已签字维保员", signedListSplit);
				}
				// 未签字维保员 实际执行人与已签字维保员的差集
				if(Func.isNotEmpty(signedList) && Func.isNotEmpty(actualExecuteList)) {
					List<String> unsignedList = new ArrayList<>(actualExecuteList);
					unsignedList.removeAll(signedList);
					elementMap.put("未签字维保员", unsignedList.toArray(new String[0]));
				}
				elementMap.put("组别", planListVo.getGroupName().split(","));
				elementMap.put("项目", planListVo.getBuildingName());
				elementMap.put("梯号", planListVo.getElevatorAddress());
				elementMap.put("电梯状态",
					new Integer(1).equals(planListVo.getIsStop()) ? "正常运行" : "停梯"
				);
				String templateNames = planListVo.getTemplateNames();
				// 1747154112313532417-天雄测试模板,1763081415090966530-天雄保养模板,3-半年保养,4-年度保养
				// 只获取 - 与 , 之间的字符串
				if(!Func.isNull(templateNames)){
					String[] templateNamesArray = templateNames.split(",");
					List<String> templateNameList = new ArrayList<>();
					for (String templateName : templateNamesArray) {
						String[] templateNameArray = templateName.split("-");
						if (templateNameArray.length > 1) {
							templateNameList.add(templateNameArray[1]);
						}
					}
					elementMap.put("任务描述", templateNameList.toArray(new String[0]));
				}
				if(!Func.isNull(planListVo.getPlanDate())){
					String planDateString = planListVo.getPlanDate();
					// yyyy-MM-dd 的字符串格式化成 Date
					Date planDate = DateUtil.parse(planDateString, "yyyy-MM-dd");
					elementMap.put("计划时间", planDate.getTime());
				}
				if(!Func.isNull(planListVo.getPlanStartTime())){
					String planStartTimeString = planListVo.getPlanStartTime();
					Date planStartTime = DateUtil.parse(planStartTimeString, "yyyy-MM-dd HH:mm:ss");
					elementMap.put("开始时间", planStartTime.getTime());
				}
				// 表格内的完成时间忽略，因为检索的就是没有完成时间的，其他字段暂时未知，先同步上去再说
				if(!Func.isNull(planListVo.getImageNums())){
					elementMap.put("图片数量",new Integer(planListVo.getImageNums()));
				}else{
					elementMap.put("图片数量",0);
				}
				elementMap.put("当前状态",planListVo.getPlanStatusName());
				elementMap.put("时效",planListVo.getOverdueDayName());
				elementMap.put("时长标识",planListVo.getWorkMinuteName());
				if(!Func.isNull(planListVo.getWorkMinute())){
					elementMap.put("时长(分钟)",String.valueOf(planListVo.getWorkMinute()));
				}
				// 评分、有效判定、状态等因为未评分，忽略
				elementMap.put("调整证明", planListVo.getDeferWarrantName());
				elementMap.put("计划调整状态", planListVo.getDeferTypeName());
				// 已提交调整数量
				if(!Func.isNull(planListVo.getDeferCounts())){
					elementMap.put("已提交调整数量", String.valueOf(planListVo.getDeferCounts()));
				}
				// 逾期描述
				boolean isDesc = false;
				if(!Func.isNull(planListVo.getIsOverdueTomorrow())){
					isDesc = planListVo.getIsOverdueTomorrow();
				}
				elementMap.put("逾期",
					new Integer(1).equals(planListVo.getOverdueType()) ? "已逾期" :
						new Integer(2).equals(planListVo.getOverdueType()) ? "未逾期" + (isDesc ? "(明天即将违规)" : "") : "非年审梯"
				);
				// 任务年审类型
				elementMap.put("任务年审类型", new Integer(2).equals(planListVo.getAuditType()) ? "年审" : "非年审" );
				// 电梯类型
				elementMap.put("电梯类型", new Integer(0).equals(planListVo.getUseType()) ? "年审" : "非年审" );
				// 签到签退异常状态
				if(!Func.isEmpty(planListVo.getPlanSignStatusList())){
					// 拼接字符串
					StringBuilder signStatusBuilder = new StringBuilder();
					planListVo.getPlanSignStatusList().forEach(t -> {
						if(!Func.isNull(t.getUserName())){
							signStatusBuilder.append(t.getUserName()).append(" ");
						}
						if(!Func.isNull(t.getSignStatusName())){
							signStatusBuilder.append(t.getSignStatusName()).append(" ");
						}
						if(!Func.isNull(t.getSignOutStatusName())){
							signStatusBuilder.append(t.getSignOutStatusName()).append(" ");
						}
					});
					elementMap.put("签到签退异常状态", signStatusBuilder.toString());
				}
				if(!Func.isNull(planListVo.getCommitTime())){
					elementMap.put("提交时间", planListVo.getCommitTime().getTime());
				}
				// 维保签字时间
				if(!Func.isNull(planListVo.getMaintainSignatureTime())){
					elementMap.put("维保签字时间", planListVo.getMaintainSignatureTime().getTime());
				}
				element.setFields(elementMap);
				records.add(element);
			}
			batchDTO.setRecords(records);
			// 3. 调用飞书API，更新数据表
			String finalResult = feiShuDocumentService.commandCompareUpdateBatch(appToken,tableId,batchDTO,"梯无忧_保养工单任务ID");
			List<JSONObject> targetGroupObjects = feiShuDocumentService.commandQueryGroupsBatch();
			List<String> chatIds = new ArrayList<>();
			targetGroupObjects.forEach(t -> chatIds.add(t.getString("chat_id")));
			// 发送消息
			chatIds.forEach(c -> {
				// 组装数据
				JSONObject bodyJson = new JSONObject();
				bodyJson.put("receive_id", c);
				bodyJson.put("msg_type", "text");
				HashMap<String, String> contentMap = new HashMap<>(2);
				String message = "定时器或表格按钮触发更新"+FeiShuDocumentEnum.getDescription(appToken,tableId)+"结果：" + finalResult;
				contentMap.put("text", message);
				// 将 contentMap 转换成 JSON 格式
				bodyJson.put("content", JSON.toJSONString(contentMap));
				feiShuDocumentService.commandSendGroupMessage(bodyJson.toJSONString());
			});
			XxlJobHelper.handleSuccess("定时任务更新凤仪的飞书保养工单-逾期风险数据表-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("定时任务更新凤仪的飞书保养工单-逾期风险数据表-[执行]失败"+e);
		}
	}

	@XxlJob("galaxyElevatorMaintenanceOverdueDataJob")
	public void galaxyElevatorMaintenanceOverdueDataJob(){
		XxlJobHelper.handleSuccess("定时任务更新凤仪的飞书保养工单-逾期风险数据表-[执行]开始");
		try{
			// 1. 数据准备：appToken，tableId，构造查询条件，复用分页查询逻辑，稍作修改，查询全部数据
			String appToken = FeiShuDocumentEnum.ELEVATOR_MAINTENANCE_OVERDUE_DATA.getAppToken();
			String tableId = FeiShuDocumentEnum.ELEVATOR_MAINTENANCE_OVERDUE_DATA.getTableId();
			feiShuDocumentService.commandDistinctByKeyAndUpdateTime(appToken,tableId,"梯无忧_保养工单任务ID","最后更新时间");
			PlanSearchDTO planSearchDTO = new PlanSearchDTO();
			planSearchDTO.setCurrent(null);
			planSearchDTO.setSize(null);
			Date beginTime = new Date(0L);
			// 当天 23:59:59
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.HOUR_OF_DAY, 23);
			calendar.set(Calendar.MINUTE, 59);
			calendar.set(Calendar.SECOND, 59);
			Date endTime = calendar.getTime();
			planSearchDTO.setBeginCreateTime(beginTime);
			planSearchDTO.setEndCreateTime(endTime);
			List<Integer> planStatusList = new ArrayList<>();
			// 待开始+进行中+已提交
			planStatusList.add(TaskStatusEnum.BY_DISABLE.getStatus());
			planStatusList.add(TaskStatusEnum.BY_PROCESSED.getStatus());
			planStatusList.add(TaskStatusEnum.BY_FINISH.getStatus());
			planSearchDTO.setPlanStatus(planStatusList);
			List<PlanListVo> targetList = maintainPlanContentService.planListNewLark(planSearchDTO);

			// 2. 数据封装、数据处理
			FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
			List<FeiShuFieldsDTO> records = new ArrayList<>();
			for (PlanListVo planListVo : targetList) {
				FeiShuFieldsDTO element = new FeiShuFieldsDTO();
				Map<String, Object> elementMap = new HashMap<>(30);
				elementMap.put("梯无忧_保养工单任务ID", String.valueOf(planListVo.getPlanId()));
				elementMap.put("梯无忧_电梯快速识别码", planListVo.getElevatorNum());
				// 执行人
				if(!Func.isNull(planListVo.getRealNames())){
					String[] realNamesArray = planListVo.getRealNames().split(",");
					elementMap.put("执行人", realNamesArray);
				}
				// 实际执行人
				List<PlanSignStatusVo> planSignStatusList = planListVo.getPlanSignStatusList();
				List<String> actualExecuteList = new ArrayList<>();
				if(!Func.isEmpty(planSignStatusList)){
					planSignStatusList.stream().map(PlanSignStatusVo::getUserName).forEach(actualExecuteList::add);
					elementMap.put("实际执行人", actualExecuteList.toArray(new String[0]));
				}
				// 已签字维保员
				List<String> signedList = new ArrayList<>();
				if(!Func.isNull(planListVo.getSignNames())){
					String[] signedListSplit = planListVo.getSignNames().split(",");
					signedList = Arrays.asList(signedListSplit);
					elementMap.put("已签字维保员", signedListSplit);
				}
				// 未签字维保员 实际执行人与已签字维保员的差集
				if(Func.isNotEmpty(signedList) && Func.isNotEmpty(actualExecuteList)) {
					List<String> unsignedList = new ArrayList<>(actualExecuteList);
					unsignedList.removeAll(signedList);
					elementMap.put("未签字维保员", unsignedList.toArray(new String[0]));
				}
				elementMap.put("组别", planListVo.getGroupName().split(","));
				elementMap.put("项目", planListVo.getBuildingName());
				elementMap.put("梯号", planListVo.getElevatorAddress());
				elementMap.put("电梯状态",
					new Integer(1).equals(planListVo.getIsStop()) ? "正常运行" : "停梯"
				);
				String templateNames = planListVo.getTemplateNames();
				// 1747154112313532417-天雄测试模板,1763081415090966530-天雄保养模板,3-半年保养,4-年度保养
				// 只获取 - 与 , 之间的字符串
				if(!Func.isNull(templateNames)){
					String[] templateNamesArray = templateNames.split(",");
					List<String> templateNameList = new ArrayList<>();
					for (String templateName : templateNamesArray) {
						String[] templateNameArray = templateName.split("-");
						if (templateNameArray.length > 1) {
							templateNameList.add(templateNameArray[1]);
						}
					}
					elementMap.put("任务描述", templateNameList.toArray(new String[0]));
				}
				if(!Func.isNull(planListVo.getPlanDate())){
					String planDateString = planListVo.getPlanDate();
					// yyyy-MM-dd 的字符串格式化成 Date
					Date planDate = DateUtil.parse(planDateString, "yyyy-MM-dd");
					elementMap.put("计划时间", planDate.getTime());
				}
				if(!Func.isNull(planListVo.getPlanStartTime())){
					String planStartTimeString = planListVo.getPlanStartTime();
					Date planStartTime = DateUtil.parse(planStartTimeString, "yyyy-MM-dd HH:mm:ss");
					elementMap.put("开始时间", planStartTime.getTime());
				}
				// 表格内的完成时间忽略，因为检索的就是没有完成时间的，其他字段暂时未知，先同步上去再说
				if(!Func.isNull(planListVo.getImageNums())){
					elementMap.put("图片数量",new Integer(planListVo.getImageNums()));
				}else{
					elementMap.put("图片数量",0);
				}
				elementMap.put("当前状态",planListVo.getPlanStatusName());
				elementMap.put("时效",planListVo.getOverdueDayName());
				elementMap.put("时长标识",planListVo.getWorkMinuteName());
				if(!Func.isNull(planListVo.getWorkMinute())){
					elementMap.put("时长(分钟)",String.valueOf(planListVo.getWorkMinute()));
				}
				// 评分、有效判定、状态等因为未评分，忽略
				elementMap.put("调整证明", planListVo.getDeferWarrantName());
				elementMap.put("计划调整状态", planListVo.getDeferTypeName());
				// 已提交调整数量
				if(!Func.isNull(planListVo.getDeferCounts())){
					elementMap.put("已提交调整数量", String.valueOf(planListVo.getDeferCounts()));
				}
				// 逾期描述
				boolean isDesc = false;
				if(!Func.isNull(planListVo.getIsOverdueTomorrow())){
					isDesc = planListVo.getIsOverdueTomorrow();
				}
				elementMap.put("逾期",
					new Integer(1).equals(planListVo.getOverdueType()) ? "已逾期" :
						new Integer(2).equals(planListVo.getOverdueType()) ? "未逾期" + (isDesc ? "(明天即将违规)" : "") : "非年审梯"
				);
				// 任务年审类型
				elementMap.put("任务年审类型", new Integer(2).equals(planListVo.getAuditType()) ? "年审" : "非年审" );
				// 电梯类型
				elementMap.put("电梯类型", new Integer(0).equals(planListVo.getUseType()) ? "年审" : "非年审" );
				// 签到签退异常状态
				if(!Func.isEmpty(planListVo.getPlanSignStatusList())){
					// 拼接字符串
					StringBuilder signStatusBuilder = new StringBuilder();
					planListVo.getPlanSignStatusList().forEach(t -> {
						if(!Func.isNull(t.getUserName())){
							signStatusBuilder.append(t.getUserName()).append(" ");
						}
						if(!Func.isNull(t.getSignStatusName())){
							signStatusBuilder.append(t.getSignStatusName()).append(" ");
						}
						if(!Func.isNull(t.getSignOutStatusName())){
							signStatusBuilder.append(t.getSignOutStatusName()).append(" ");
						}
					});
					elementMap.put("签到签退异常状态", signStatusBuilder.toString());
				}
				if(!Func.isNull(planListVo.getCommitTime())){
					elementMap.put("提交时间", planListVo.getCommitTime().getTime());
				}
				// 维保签字时间
				if(!Func.isNull(planListVo.getMaintainSignatureTime())){
					elementMap.put("维保签字时间", planListVo.getMaintainSignatureTime().getTime());
				}
				element.setFields(elementMap);
				records.add(element);
			}
			batchDTO.setRecords(records);
			// 3. 调用飞书API，更新数据表
			String finalResult = feiShuDocumentService.commandCompareUpdateBatch(appToken,tableId,batchDTO,"梯无忧_保养工单任务ID");
			List<JSONObject> targetGroupObjects = feiShuDocumentService.commandQueryGroupsBatch();
			List<String> chatIds = new ArrayList<>();
			targetGroupObjects.forEach(t -> chatIds.add(t.getString("chat_id")));
			// 发送消息
			chatIds.forEach(c -> {
				// 组装数据
				JSONObject bodyJson = new JSONObject();
				bodyJson.put("receive_id", c);
				bodyJson.put("msg_type", "text");
				HashMap<String, String> contentMap = new HashMap<>(2);
				String message = "定时器或表格按钮触发更新"+FeiShuDocumentEnum.getDescription(appToken,tableId)+"结果：" + finalResult;
				contentMap.put("text", message);
				// 将 contentMap 转换成 JSON 格式
				bodyJson.put("content", JSON.toJSONString(contentMap));
				feiShuDocumentService.commandSendGroupMessage(bodyJson.toJSONString());
			});
			XxlJobHelper.handleSuccess("定时任务更新凤仪的飞书保养工单-逾期风险数据表-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("定时任务更新凤仪的飞书保养工单-逾期风险数据表-[执行]失败"+e);
		}
	}
}
